import os
import shutil
import json
import sys


def get_part_value(file_path):
    with open(
        os.path.join(os.path.dirname(os.path.dirname(file_path)), "entry.json"),
        "r",
        encoding="utf-8",
    ) as f:
        print("file_path:", file_path)
        data = json.load(f)
        return data.get("page_data")["part"]


def rename_and_copy_file(file_path, dest_folder):
    part_value = get_part_value(file_path).replace("|", "︱")
    if not part_value:
        return

    new_file_name = f"{part_value}.mp4"
    new_file_path = os.path.join(dest_folder, new_file_name)

    shutil.copy(file_path, new_file_path)


def main():
    if len(sys.argv) < 2:
        print("请输入source_folder参数")
        sys.exit(1)

    source_folder = sys.argv[1]
    dest_folder = "output"
    if not os.path.exists(dest_folder):
        os.makedirs(dest_folder)

    for root, dirs, files in os.walk(source_folder):
        for file in files:
            if file == "audio.m4s":
                file_path = os.path.join(root, file)
                rename_and_copy_file(file_path, dest_folder)


if __name__ == "__main__":
    main()
